package org.se.scut.hibernate.dao;

import java.util.List;
import java.util.Set;

import org.hibernate.Session;
import org.se.scut.hibernate.dao.model.Comment;
import org.se.scut.hibernate.dao.model.Picture;
import org.se.scut.hibernate.dao.model.UserInfo;

public class CommentDAO extends BaseDAO<Comment> {

	public int create(Comment newComment, int creatorID, int pictureID)
	{
		newComment.setCreator(DAOFactory.getUserInfoDAO()
				.find(UserInfo.class, creatorID));
		PictureDAO pictureDAO = DAOFactory.getPictureDAO();
		Picture picture = pictureDAO.find(Picture.class, pictureID);
		Set<Comment> comments = pictureDAO.getAllComments(pictureID);
		comments.add(newComment);
		picture.setComments(comments);
		pictureDAO.update(picture);
		return newComment.getId();
	}
	
	@SuppressWarnings("unchecked")
	public List<Comment> getCommentsByUserID(int userID, int from, int count)
	{
		String sql = "select c from Comment c where c.creator.id = " + userID ;
		sql += " order by c.createTime des";
		Session session = HibernateSessionFactory.getSessionFactory().openSession();
		try {
			session.beginTransaction();
			return session.createQuery(sql).setFirstResult(from)
					.setMaxResults(count).list();
		}
		finally{
			session.getTransaction().commit();
			session.close();
		}
	}
}
